package com.rajeshDyadav.hibernate.example03;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import java.util.Iterator;
import org.hibernate.Query;

public class MainClass {    
    public Session getSession() {
	Configuration configuration = new Configuration().configure();	
	ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();	
	SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
	return(sessionFactory.openSession());
    }
    
    public MyBeanEmployee insertIntoMyBeanEmployee(String empCode, String empName, String deptCode, String empContact, String empAddress, String empGender) {
	MyBeanEmployee myBeanEmployee = new MyBeanEmployee();	
	myBeanEmployee.setEmpCode(empCode);
	myBeanEmployee.setEmpName(empName);
	myBeanEmployee.setDeptCode(deptCode);
	myBeanEmployee.setEmpContact(empContact);
	myBeanEmployee.setEmpAddress(empAddress);
	myBeanEmployee.setEmpGender(empGender);	
	return(myBeanEmployee);
    }
    
    public MyBeanCustomer insertIntoMyBeanCustomer(String code, String name, String contact) {
	MyBeanCustomer myBeanCustomer = new MyBeanCustomer();
	myBeanCustomer.setCode(code);
	myBeanCustomer.setName(name);
	myBeanCustomer.setContact(contact);	
	return(myBeanCustomer);
    }
        
    public static void main(String[] args) {
	MainClass mc = new MainClass();
	Session session = null;
	String sql = "";
	try {
	    session = mc.getSession();	  
	    session.beginTransaction();
	    	    
	    MyBeanEmployee myBeanEmployee;
	    MyBeanCustomer myBeanCustomer;
	    
	    myBeanEmployee = mc.insertIntoMyBeanEmployee("0007", "XYZ", "007", "123456790", "UNKNOWN", "M");	    
	    myBeanCustomer = mc.insertIntoMyBeanCustomer("0008", "Rajesh D. Yadav", "000");
	    
	    session.save(myBeanEmployee);
	    session.save(myBeanCustomer);
	    
	    //MyBeanEmployee emp;
	    //emp = (MyBeanEmployee) session.get(MyBeanEmployee.class, 4);
	    //System.out.println(emp.getDeptCode());
	    	    
	    /*
	    sql = "select my.id, my.empName from MyBeanEmployee my where my.empCode = :code";
	    Query query = session.createQuery(sql);
	    query.setParameter("code", "0007");
	    Object row[] = null;
	    Iterator<?> it = query.iterate();
	    while (it.hasNext()) {
		row = (Object[]) it.next();
		System.out.println(row[0] + "\t" + row[1]);
	    }
	    */	    
	} catch (Exception e) {
	    session.getTransaction().rollback();
	    e.printStackTrace();
	} finally {
	    try {
		if (!session.getTransaction().wasRolledBack()) {
		    session.getTransaction().commit();
		    session.flush();
		}
		session.close();
	    } catch (Exception e) {
		e.printStackTrace();
	    }
	}
    }
}